package com.easy.common.util;

import cn.hutool.crypto.digest.DigestUtil;

public class PasswordEncode {

    private static char[] char_arr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 加密  随机盐值加密
     * @param password
     * @return
     */
    public static String encode(String password) {
        // 加密次数，范围 1 - 16
        int index_count = (int) (Math.random() * char_arr.length) + 1;
        // 加密盐值
        int index_salt = (int) (Math.random() * char_arr.length);

        String result = password;
        for (int i = 0; i < index_count; i++) {
            result = result + char_arr[index_salt];
            result = DigestUtil.md5Hex(result);
        }
        result = char_arr[index_count - 1] + result + char_arr[index_salt];
        return result;
    }

    /**
     * 成功返回true
     * @param password
     * @param decodedPassword
     * @return
     */
    public static boolean decode(String password, String decodedPassword) {
        // 加密次数
        char char_count = decodedPassword.charAt(0);
        int index_count = getIndex(char_count);
        // 加密盐值
        char char_salt = decodedPassword.charAt(decodedPassword.length() - 1);

        String tempPassword = password;
        for (int i = 0; i < index_count; i++) {
            tempPassword = tempPassword + char_salt;
            tempPassword = DigestUtil.md5Hex(tempPassword);
        }

        return decodedPassword.equals(char_count + tempPassword + char_salt);
    }

    private static int getIndex(char c) {
        for (int i = 0; i < char_arr.length; i++) {
            if (char_arr[i] == c) {
                return i + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(encode("123456"));
    }


}